package org.jeecg.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.oms.entity.SemiProductSalesOrderDetail;
import org.jeecg.modules.oms.mapper.SemiProductSalesOrderDetailMapper;
import org.jeecg.modules.oms.service.ISemiProductSalesOrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.shiro.SecurityUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 半成品销售订单明细Service实现类
 */
@Service
@Slf4j
public class SemiProductSalesOrderDetailServiceImpl extends ServiceImpl<SemiProductSalesOrderDetailMapper, SemiProductSalesOrderDetail> implements ISemiProductSalesOrderDetailService {

    @Autowired
    private SemiProductSalesOrderDetailMapper detailMapper;

    @Override
    public List<SemiProductSalesOrderDetail> getByOrderId(String orderId) {
        if (oConvertUtils.isEmpty(orderId)) {
            return null;
        }
        try {
            return detailMapper.selectByOrderId(orderId);
        } catch (Exception e) {
            log.error("根据订单ID查询明细失败: orderId={}", orderId, e);
            throw new JeecgBootException("查询订单明细失败: " + e.getMessage());
        }
    }

    @Override
    public IPage<SemiProductSalesOrderDetail> queryDetailPage(Page<SemiProductSalesOrderDetail> page, SemiProductSalesOrderDetail detail) {
        try {
            return detailMapper.selectDetailPage(page, detail);
        } catch (Exception e) {
            log.error("分页查询订单明细失败", e);
            throw new JeecgBootException("查询订单明细失败: " + e.getMessage());
        }
    }

    @Override
    public List<SemiProductSalesOrderDetail> getByMaterialId(String materialId) {
        if (oConvertUtils.isEmpty(materialId)) {
            return null;
        }
        try {
            return detailMapper.selectByMaterialId(materialId);
        } catch (Exception e) {
            log.error("根据物料ID查询明细失败: materialId={}", materialId, e);
            throw new JeecgBootException("查询订单明细失败: " + e.getMessage());
        }
    }

    @Override
    public List<SemiProductSalesOrderDetail> getByMaterialCode(String materialCode) {
        if (oConvertUtils.isEmpty(materialCode)) {
            return null;
        }
        try {
            return detailMapper.selectByMaterialCode(materialCode);
        } catch (Exception e) {
            log.error("根据物料编码查询明细失败: materialCode={}", materialCode, e);
            throw new JeecgBootException("查询订单明细失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrderDetailBatch(String orderId, List<SemiProductSalesOrderDetail> detailList) {
        try {
            if (oConvertUtils.isEmpty(orderId) || detailList == null || detailList.isEmpty()) {
                throw new JeecgBootException("参数不能为空");
            }

            // 获取当前用户信息
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String createBy = loginUser != null ? loginUser.getUsername() : "system";
            Integer tenantId = null;
            if (loginUser != null && oConvertUtils.isNotEmpty(loginUser.getRelTenantIds())) {
                tenantId = Integer.parseInt(loginUser.getRelTenantIds().split(",")[0]);
            }

            // 先删除原有明细
            deleteByOrderId(orderId);

            // 设置明细信息
            Date now = new Date();
            for (SemiProductSalesOrderDetail detail : detailList) {
                if (oConvertUtils.isEmpty(detail.getId())) {
                    detail.setId(null); // 让MyBatis-Plus自动生成ID
                }
                detail.setOrderId(orderId);
                detail.setCreateBy(createBy);
                detail.setCreateTime(now);
                detail.setTenantId(tenantId);

                // 计算金额
                if (detail.getQuantity() != null && detail.getUnitPrice() != null) {
                    BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
                    detail.setAmount(amount);
                }

                // 验证明细数据
                if (!validateDetail(detail)) {
                    throw new JeecgBootException("明细数据验证失败");
                }
            }

            // 批量插入
            boolean result = this.saveBatch(detailList);
            if (!result) {
                throw new JeecgBootException("批量保存明细失败");
            }

            log.info("批量保存订单明细成功: orderId={}, count={}", orderId, detailList.size());
            return true;
        } catch (Exception e) {
            log.error("批量保存订单明细失败", e);
            throw new JeecgBootException("保存订单明细失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderDetailBatch(List<SemiProductSalesOrderDetail> detailList) {
        try {
            if (detailList == null || detailList.isEmpty()) {
                return true;
            }

            // 获取当前用户信息
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String updateBy = loginUser != null ? loginUser.getUsername() : "system";

            // 设置更新信息
            Date now = new Date();
            for (SemiProductSalesOrderDetail detail : detailList) {
                detail.setUpdateBy(updateBy);
                detail.setUpdateTime(now);

                // 重新计算金额
                if (detail.getQuantity() != null && detail.getUnitPrice() != null) {
                    BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
                    detail.setAmount(amount);
                }

                // 验证明细数据
                if (!validateDetail(detail)) {
                    throw new JeecgBootException("明细数据验证失败");
                }
            }

            // 批量更新
            int result = detailMapper.batchUpdate(detailList);
            if (result <= 0) {
                throw new JeecgBootException("批量更新明细失败");
            }

            log.info("批量更新订单明细成功: count={}", detailList.size());
            return true;
        } catch (Exception e) {
            log.error("批量更新订单明细失败", e);
            throw new JeecgBootException("更新订单明细失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByOrderId(String orderId) {
        try {
            if (oConvertUtils.isEmpty(orderId)) {
                return false;
            }
            this.remove(new QueryWrapper<SemiProductSalesOrderDetail>().eq("order_id", orderId));
            return true;
        } catch (Exception e) {
            log.error("删除订单明细失败: orderId={}", orderId, e);
            throw new JeecgBootException("删除订单明细失败: " + e.getMessage());
        }
    }

    @Override
    public BigDecimal calculateTotalAmount(String orderId) {
        try {
            if (oConvertUtils.isEmpty(orderId)) {
                return BigDecimal.ZERO;
            }
            BigDecimal result = detailMapper.calculateTotalAmount(orderId);
            return result != null ? result : BigDecimal.ZERO;
        } catch (Exception e) {
            log.error("计算订单总金额失败: orderId={}", orderId, e);
            throw new JeecgBootException("计算订单总金额失败: " + e.getMessage());
        }
    }

    @Override
    public BigDecimal calculateTotalCost(String orderId) {
        try {
            if (oConvertUtils.isEmpty(orderId)) {
                return BigDecimal.ZERO;
            }
            BigDecimal result = detailMapper.calculateTotalCost(orderId);
            return result != null ? result : BigDecimal.ZERO;
        } catch (Exception e) {
            log.error("计算订单总成本失败: orderId={}", orderId, e);
            throw new JeecgBootException("计算订单总成本失败: " + e.getMessage());
        }
    }

    @Override
    public Integer countByOrderId(String orderId) {
        try {
            if (oConvertUtils.isEmpty(orderId)) {
                return 0;
            }
            Integer result = detailMapper.countByOrderId(orderId);
            return result != null ? result : 0;
        } catch (Exception e) {
            log.error("统计订单明细数量失败: orderId={}", orderId, e);
            throw new JeecgBootException("统计订单明细数量失败: " + e.getMessage());
        }
    }

    @Override
    public boolean updateDetailAmount(String id, Integer quantity, BigDecimal unitPrice, String updateBy) {
        try {
            if (oConvertUtils.isEmpty(id) || quantity == null || unitPrice == null) {
                return false;
            }

            BigDecimal amount = unitPrice.multiply(new BigDecimal(quantity));
            int result = detailMapper.updateAmount(id, quantity, unitPrice, amount, updateBy);
            return result > 0;
        } catch (Exception e) {
            log.error("更新明细金额失败: id={}", id, e);
            throw new JeecgBootException("更新明细金额失败: " + e.getMessage());
        }
    }

    @Override
    public boolean validateDetail(SemiProductSalesOrderDetail detail) {
        if (detail == null) {
            return false;
        }

        // 验证必填字段
        if (oConvertUtils.isEmpty(detail.getOrderId())) {
            log.error("订单ID不能为空");
            return false;
        }
        if (oConvertUtils.isEmpty(detail.getMaterialId())) {
            log.error("物料ID不能为空");
            return false;
        }
        if (oConvertUtils.isEmpty(detail.getMaterialCode())) {
            log.error("物料编码不能为空");
            return false;
        }
        if (oConvertUtils.isEmpty(detail.getMaterialName())) {
            log.error("物料名称不能为空");
            return false;
        }
        if (detail.getQuantity() == null || detail.getQuantity() <= 0) {
            log.error("数量必须大于0");
            return false;
        }
        if (detail.getUnitPrice() == null || detail.getUnitPrice().compareTo(BigDecimal.ZERO) < 0) {
            log.error("单价不能为负数");
            return false;
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrderDetail(SemiProductSalesOrderDetail detail) {
        try {
            if (!validateDetail(detail)) {
                throw new JeecgBootException("明细数据验证失败");
            }

            // 获取当前用户信息
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (loginUser != null) {
                detail.setCreateBy(loginUser.getUsername());
                if (detail.getTenantId() == null && oConvertUtils.isNotEmpty(loginUser.getRelTenantIds())) {
                    detail.setTenantId(Integer.parseInt(loginUser.getRelTenantIds().split(",")[0]));
                }
            }

            // 计算金额
            if (detail.getQuantity() != null && detail.getUnitPrice() != null) {
                BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
                detail.setAmount(amount);
            }

            detail.setCreateTime(new Date());

            boolean result = this.save(detail);
            if (!result) {
                throw new JeecgBootException("保存明细失败");
            }

            log.info("添加订单明细成功: id={}", detail.getId());
            return true;
        } catch (Exception e) {
            log.error("添加订单明细失败", e);
            throw new JeecgBootException("添加订单明细失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderDetail(SemiProductSalesOrderDetail detail) {
        try {
            if (!validateDetail(detail)) {
                throw new JeecgBootException("明细数据验证失败");
            }

            // 获取当前用户信息
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (loginUser != null) {
                detail.setUpdateBy(loginUser.getUsername());
            }

            // 重新计算金额
            if (detail.getQuantity() != null && detail.getUnitPrice() != null) {
                BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
                detail.setAmount(amount);
            }

            detail.setUpdateTime(new Date());

            boolean result = this.updateById(detail);
            if (!result) {
                throw new JeecgBootException("更新明细失败");
            }

            log.info("更新订单明细成功: id={}", detail.getId());
            return true;
        } catch (Exception e) {
            log.error("更新订单明细失败", e);
            throw new JeecgBootException("更新订单明细失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrderDetail(String id) {
        try {
            if (oConvertUtils.isEmpty(id)) {
                throw new JeecgBootException("明细ID不能为空");
            }

            boolean result = this.removeById(id);
            if (!result) {
                throw new JeecgBootException("删除明细失败");
            }

            log.info("删除订单明细成功: id={}", id);
            return true;
        } catch (Exception e) {
            log.error("删除订单明细失败", e);
            throw new JeecgBootException("删除订单明细失败: " + e.getMessage());
        }
    }
}
